package com.ai.service.impl;

import com.ai.constant.SystemConst;
import com.ai.dao.mapper.BfmUserMapper;
import com.ai.dao.mapper.UamToEdpLogMapper;
import com.ai.pojo.BfmUser;
import com.ai.pojo.TngpUserRef;
import com.ai.request.TyrzAccountReq;
import com.ai.request.TyrzOrgInfoReq;
import com.ai.response.TyrzAccountDTO;
import com.ai.response.UamToEdpLog;
import com.ai.service.ITyrzService;
import com.ai.utils.DateFormatUtils;
import com.ai.utils.DesEncrypt;
import com.ai.utils.MD5Utils;
import com.alibaba.fastjson.JSON;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.beans.Transient;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author fengs
 * @description 统一认证
 * @date 2022/7/6 11:20
 */
@Service
public class TyrzServiceImpl implements ITyrzService {

//    @Autowired
//    BasicPlatformUserMapper platformUserMapper;

    @Autowired
    BfmUserMapper bfmUserMapper;

    @Autowired
    UamToEdpLogMapper uamToEdpLogMapper;

    @Override
    public TyrzAccountDTO accountSync(TyrzAccountReq req) {

        // 记录日志
        UamToEdpLog uamToEdpLog = new UamToEdpLog();
        uamToEdpLog.setIp(req.getIp());
        uamToEdpLog.setMainAccountCode(req.getMain_account_code());
        uamToEdpLog.setUserInfoNew(JSON.toJSONString(req));

        TyrzAccountDTO accountDTO = new TyrzAccountDTO();
        accountDTO.setRsp_code("0000");
        accountDTO.setRsp_desc("成功");
        accountDTO.setTransaction_id(req.getTransaction_id());
        accountDTO.setResponse_time(DateFormatUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss"));

        // 解密签名，进行签名校验
        String checkSignResult = checkSign(req);
        if (!StringUtils.isEmpty(checkSignResult)) { // 签名校验失败
            uamToEdpLog.setUserInfoOld(checkSignResult);
            uamToEdpLogMapper.insertLog(uamToEdpLog);

            accountDTO.setRsp_code("1111");
            accountDTO.setRsp_desc(checkSignResult);
            return accountDTO;
        }
        try {
            BfmUser bfmUser = new BfmUser();
//            bfmUser.setMainAccountCode(req.getMain_account_code());
            String main_account_code = req.getMain_account_code();
            //账号问题特殊处理
            if ("huangbo6".equals(main_account_code)) {
                main_account_code = "huangbo";
            }
            if ("liunian10".equals(main_account_code)) {
                main_account_code = "liunian";
            }
//            if ("liunian".equals(main_account_code)) {
//                accountDTO.setRsp_code("-1");
//                accountDTO.setRsp_desc("没有进行任何操作");
//                return accountDTO;
//            }
            if ("mokundong".equals(main_account_code)) {
                main_account_code = "Mokundong";
            }
            bfmUser.setUserCode(main_account_code);
            bfmUser.setPhone(DesEncrypt.TriDesDecrypt(req.getPhone_number()));
            bfmUser.setUserName(DesEncrypt.TriDesDecrypt(req.getUser_name()));
            // 获取组织ID（第一个T主职）
//            bfmUser.setMainOrgId(getOrgId(req.getOrg_info()));

            BfmUser oldUser = bfmUserMapper.selectUserByMainCode(bfmUser);
            uamToEdpLog.setUserInfoOld(JSON.toJSONString(oldUser));
            uamToEdpLogMapper.insertLog(uamToEdpLog);

            int count = 0;
            // 校验通过，根据不同操作类型，进行对应的处理 A：新增，M：修改，D：注销
            if ("A".equals(req.getAction_code())) {
                //只能前往AI平台进行账号创建
                accountDTO.setRsp_code("2222");
                accountDTO.setRsp_desc("请前往AI通用平台进行账号创建");
                return accountDTO;
//                if (null != oldUser) {
//                    accountDTO.setRsp_code("2222");
//                    accountDTO.setRsp_desc("人员主数据编码已存在");
//                    return accountDTO;
//                }
//                bfmUser.setCertiNumber(DesEncrypt.TriDesDecrypt(req.getCerti_number()));
                
//                count = addAccount(bfmUser);
            } else if ("M".equals(req.getAction_code())) {
                if (null == oldUser) {
                    accountDTO.setRsp_code("3333");
                    accountDTO.setRsp_desc("人员主数据编码不存在");
                    return accountDTO;
                }
                bfmUser.setUserId(oldUser.getUserId());
                count = modifyAccount(bfmUser);
            } else if ("D".equals(req.getAction_code())) {
                if (null == oldUser) {
                    accountDTO.setRsp_code("4444");
                    accountDTO.setRsp_desc("人员主数据编码不存在");
                    return accountDTO;
                }
                int flag = saveUserHis(bfmUser);
                //判断账号是否为，超级管理员、企业管理员
                Map<String, Object> map = isManager(bfmUser);
                String parent_id = MapUtils.getString(map, "parent_id");
                if (StringUtils.isEmpty(parent_id)) {
                    //若是，则不要进行注销，往转换表插入数据
                    insertStaffTrans(bfmUser);
                }else if (!StringUtils.isEmpty(parent_id) && flag > 0) {
                    count = deleteAccount(bfmUser);
                }
            }
            if (count == 0) {
                accountDTO.setRsp_code("7777");
                accountDTO.setRsp_desc("未影响任何相关数据");
                return accountDTO;
            }

        } catch (Exception ex) {
            accountDTO.setRsp_code("9999");
            accountDTO.setRsp_desc("系统异常，原因："+ex.getMessage());
            return accountDTO;
        }

        return accountDTO;
    }



    @Override
    public BfmUser queryUserByMainCode(String mainAccountCode) {
        BfmUser user = new BfmUser();
//        user.setMainAccountCode(mainAccountCode);
        user.setUserCode(mainAccountCode);
        return bfmUserMapper.selectUserByMainCode(user);
    }


    @Transient
    @Override
    public int addAccount(BfmUser userInfo) {
        userInfo.setUserId(bfmUserMapper.getUserIdBySeq());
        userInfo.setState("A");
//        userInfo.setUserCode(userInfo.getMainAccountCode());
        userInfo.setUserCode(userInfo.getUserCode());
        userInfo.setUserEffDate(new Date()); // 只设置生效时间，不设置失效时间，默认长期有效
        userInfo.setCreatedDate(new Date());
        userInfo.setIsLocked("N");
        userInfo.setPortalId(1);
        // 密码处理
        userInfo.setPwd(createNewPwd(userInfo.getUserCode()));
        int count = bfmUserMapper.addAccount(userInfo); // 新增用户基础信息

        // 新增用户关联信息
        TngpUserRef userRef = new TngpUserRef();
        userRef.setUserId(userInfo.getUserId());
//        userRef.setOrgId(null); // 用户组织默认空，人主组织和工厂组织不同
        userRef.setComAcctId(1L);
        userRef.setParentId(1L);
        userRef.setUserType(1);
        count += bfmUserMapper.addUserRef(userRef);
        return count;
    }

    @Transient
    @Override
    public int modifyAccount(BfmUser userInfo) {
        int count = bfmUserMapper.modifyAccount(userInfo);
        // 修改用户关联信息(组织)
//        TngpUserRef userRef = new TngpUserRef();
//        userRef.setUserId(userInfo.getUserId());
//        userRef.setOrgId(userInfo.getOrgId());
//        count += bfmUserMapper.modifyUserRef(userRef);
        return count;
    }

    @Override
    public int deleteAccount(BfmUser userInfo) {
        return bfmUserMapper.deleteAccount(userInfo);
    }

    public int saveUserHis(BfmUser bfmUser) {
        return bfmUserMapper.saveUserHis(bfmUser);
    }

    public Map<String, Object> isManager(BfmUser bfmUser) {
        return bfmUserMapper.queryIsManager(bfmUser);
    }

    public int insertStaffTrans(BfmUser bfmUser) {
        return bfmUserMapper.insertStaffTrans(bfmUser);
    }

    @Override
    public Map<String, Object> queryTransByAccountCode(String mainAccountCode) {
        return bfmUserMapper.queryTransByAccountCode(mainAccountCode);
    }

    /**
     * 统一认证签名校验
     * @param req
     * @return 通过返回null， 失败返回失败原因字符串
     */
    private static String checkSign(TyrzAccountReq req) {

        if (StringUtils.isEmpty(req.getSign())) {
            return "签名为空";
        }
        try {
            String sign = DesEncrypt.decryptpar(req.getSign(), SystemConst.TYRZ_KEY);
            TyrzAccountReq signObj = JSON.parseObject(sign, TyrzAccountReq.class);
            // 解密出的身份证号码、手机号和明文相同则校验通过
            if (req.getCerti_number().equals(signObj.getCerti_number())
                    && req.getPhone_number().equals(signObj.getPhone_number())) {
                return null;
            } else {
                return "签名信息不一致";
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return "签名校验失败";
        }
    }

    /**
     * 得到主职的组织编号
     * @param orgList
     * @return
     */
    private Long getOrgId(List<TyrzOrgInfoReq> orgList) {
        if (CollectionUtils.isEmpty(orgList)) {
            return null;
        }
        for (TyrzOrgInfoReq org : orgList) {
            if ("T".equals(org.getIs_main())) {
                return Long.valueOf(org.getOrg_id());
            }
        }
        return Long.valueOf(orgList.get(0).getOrg_id());
    }

    /**
     * 新用户创建密码
     * 组成规则：主数据平台编码+M@123
     * 加密规则：
     * @param mainAccountCode 主数据平台编码
     * @return
     */
    private static String createNewPwd(String mainAccountCode) {
        String pwd = mainAccountCode + SystemConst.PWD_SUFFIX;
        return MD5Utils.encryptToSjgc(pwd, mainAccountCode);
    }

    public static void main(String[] args) {

        System.out.println(DesEncrypt.TriDesDecrypt("12197B02144A160672CD09583ABD5838"));
//        TyrzAccountReq req = new TyrzAccountReq();
//        req.setMain_account_code("aidaohan");
//        System.out.println(createNewPwd(req.getMain_account_code()));
//
//        System.out.println("checkpwd ==="+MD5Utils.encryptToSjgc("111aaa@sc", "1010101"));

//        req.setCerti_number("1878C51D35EDBA354FFDE019F03B293581F5D3B74FE3EB05");
//        req.setPhone_number("36CF7330FA2E3999DECAA9EEB7000D27");
//        req.setSign("7wnGpZhWTSo3V3wYFJ1PokE+epHqetLPqX4LR9lHuDon94DmiJgBoPbx7HnPcTkmp8+kayXY1ufIFGm0Ulrna4HP+2gkzFISrzeqepp/q4XvWDEu+P/Xb1mV9mbgmHyJNk/mMGo9+6cWPc0bv0GgwBZtPrAEXSW07IOV/7bM8fVdgvZtwvJebpSfFsrROjhsirX3ZEjdghCNzG9MKsqGiPm5y2V3fljl7qye0EYneSBaO8tv1z0YcDujU03wtHAxMUnF8ROAtwSVmGSQa6IdqMTazTtYPdogkIqEUptfbCDIjYKZNSO16CJT4S66hRH3w5VXaJzbbLasJwHJwBx8t5Ke5WDfqenP+7ON9rjDPDScqkmntliCuJvDbuc/oTG18bBR3CLEENnvML0BNjVY9bVeBaqhIEi9fv8OcE/4oaGMkbtuz8E4zekaJMQ0ANfXPUK/E22mZxbRe3dF2Z6x2ckx5BNvmBG2w5XUW+Xw5E76zh8+/D+trL+ciQmXh5UxubzloPICDFo=");
//        System.out.println(checkSign(req));


    }
}
